package com.project.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.project.model.CommentModel;
import com.project.model.MemberModel;
import com.project.service.CommentService;
import com.project.service.MemberService;

@Controller
@RequestMapping(value = "/comment")
public class CommentController {
	private static Logger logger = LoggerFactory.getLogger(CommentController.class);
	
	@Value("${file.upload.path}")
    private String rootPath;
	
	@Autowired
	private CommentService commentService;
	
	@Autowired
	private MemberService memberService;
	
	@RequestMapping(value = "", method = RequestMethod.POST, produces = "application/json;charset=utf8")
	public @ResponseBody Map<String, Object> comment(@RequestParam("upload_file") MultipartFile[] files, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		HttpSession session = request.getSession();
		if (null == session.getAttribute("userId")) {
			map.put("code", "-1");
			map.put("msg", "登录已失效，请重新登录");
			return map;
		}
		
		int environment = 0;
		try {
			environment = Integer.parseInt(request.getParameter("environment"));
		} catch (Exception e) {
			// TODO: handle exception
			map.put("code", "0");
			map.put("msg", "请给环境打个分");
			return map;
		}
		
		int service_star = 0;
		try {
			service_star = Integer.parseInt(request.getParameter("service_star"));
		} catch (Exception e) {
			// TODO: handle exception
			map.put("code", "0");
			map.put("msg", "请给服务打个分");
			return map;
		}
		
		int taste = 0;
		try {
			taste = Integer.parseInt(request.getParameter("taste"));
		} catch (Exception e) {
			// TODO: handle exception
			map.put("code", "0");
			map.put("msg", "请给口味打个分");
			return map;
		}
		
		int shop_id = 0;
		try {
			shop_id = Integer.parseInt(request.getParameter("shop_id"));
		} catch (Exception e) {
			// TODO: handle exception
			map.put("code", "0");
			map.put("msg", "要评论的店铺不存在");
			return map;
		}
		if (null == request.getParameter("content") || "".equals(request.getParameter("content"))) {
			map.put("code", "0");
			map.put("msg", "请填写评论内容");
			return map;
		}
		double a = (service_star + environment + taste) / 3;
		DecimalFormat df = new DecimalFormat("0.#");
		
		BigDecimal total_star = new BigDecimal(df.format(a));
		int member_id = (int)session.getAttribute("userId");
		MemberModel memberModel = memberService.getBasisMemberModelById(member_id);
		String member_name = memberModel.getNick_name();
		String content = request.getParameter("content");
		
		CommentModel commentModel = new CommentModel();
		commentModel.setContent(content);
		commentModel.setTotalStar(total_star);
		commentModel.setServiceStar(service_star);
		commentModel.setEnvironment(environment);
		commentModel.setTaste(taste);
		commentModel.setShopId(shop_id);
		commentModel.setMemberId(member_id);
		commentModel.setMemberName(member_name);
		commentModel.setState(0);
		
		String[] picArr = null;
		if (files.length > 0) {
			try {
				picArr = uploadImg(files, shop_id);
			} catch (IOException e) {
				map.put("code", "0");
				map.put("msg", "图片上传失败");
				return map;
			}
		}
		commentService.addComment(commentModel, picArr);
		map.put("code", "1");
		map.put("msg", "评论发表成功");
		return map;
	}
	
	private String[] uploadImg(MultipartFile[] files, int shopId) throws IOException {
		String[] picArr = new String[files.length];
		for (int i=0; i<files.length; i++) {
			MultipartFile file = files[i];
			if (!file.isEmpty()) {
	            InputStream in = null;
	            OutputStream out = null;
	            File dir = null;
	            String fileName = null;
	            String suffixName = null;

	            try {
	            	////根目录》功能目录》日期目录》文件名[会员ID+时间戳]
	            	String funName = "/commnet/"+shopId;
	            	
	                dir = new File(rootPath + funName);
	                
	                if (!dir.exists())
	                    dir.mkdirs();
	                fileName = shopId + "_" + i + "_" + System.currentTimeMillis();
	                suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
	                File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName + "." + suffixName);
	                in = file.getInputStream();
	                out = new FileOutputStream(serverFile);
	                byte[] b = new byte[1024];
	                int len = 0;
	                while ((len = in.read(b)) > 0) {
	                    out.write(b, 0, len);
	                }
	                out.close();
	                in.close();
	                logger.info("Server File Location=" + serverFile.getAbsolutePath());
	                picArr[i] = funName + File.separator + fileName + "." + suffixName;
	            } catch (Exception e) {
	            	return null;
	            } finally {
	                if (out != null) {
	                    out.close();
	                    out = null;
	                }
	                if (in != null) {
	                    in.close();
	                    in = null;
	                }
	            }
	        } else {
	        	return null;
	        }
		}
		return picArr;
	}
}